#!/usr/bin/env python
# _*_coding:utf-8_*_

"""
@Time :    2019/9/25 11:30
@Author:  ThinHeader
@File: tools.py
@Software: PyCharm
"""
import json
import logging

from common.views import get_obj
from common.wx.WXBizMsgCrypt import WxCryptConfig
from common.wx.lib import WeixinHelper
from open.models import ComponentAccessToken, WxPublicAccess, WxPublicInfo, WxPublicMapShop
from open.tasks import update_public_info, update_public_token

logger = logging.getLogger('qixiaobao')


def get_public_token_and_info(auth_code, shop_id):
    """用授权码获取公众号token和信息"""
    # logger.debug('auth_code:%s, shop_id:%s' % (auth_code, shop_id))
    token = ComponentAccessToken.objects.all().first().token
    data = json.loads(WeixinHelper.getQueryAuth(WxCryptConfig.app_id, auth_code, token))
    logger.debug('get_public_token_and_info(getQueryAuth): %s' % data)
    info = data['authorization_info']
    app_id = info['authorizer_appid']
    access_token = info['authorizer_access_token']
    refresh_token = info['authorizer_refresh_token']
    expires_in = info['expires_in']
    xpa, create = WxPublicAccess.objects.get_or_create(app_id=app_id,
                                                       defaults={
                                                           'access_token': access_token,
                                                           'expires': expires_in,
                                                           'refresh_token': refresh_token,
                                                           'status': WxPublicAccess.STATUS_VALID
                                                       })
    wx_type = update_public_info(app_id)
    # 建立店铺和微信公众号的映射
    pm = get_obj(WxPublicMapShop, shop_id=shop_id, status=WxPublicMapShop.STATUS_VALID)
    if pm:
        if wx_type == WxPublicInfo.WX_PUBLISH:
            pm.app_id = app_id
        else:
            pm.xcx_id = app_id
        pm.save()
    else:
        if wx_type == WxPublicInfo.WX_PUBLISH:
            pm = WxPublicMapShop.objects.create(shop_id=shop_id, app_id=app_id, status=WxPublicMapShop.STATUS_VALID)
        else:
            pm = WxPublicMapShop.objects.create(shop_id=shop_id, xcx_id=app_id, status=WxPublicMapShop.STATUS_VALID)
    # 刷新ticket
    data_ticket = json.loads(WeixinHelper.getJsapiTicket(access_token))
    # logger.debug('get_public_token_and_info(getJsapiTicket): %s' % data_ticket)
    if 'ticket' in data_ticket:
        xpa.ticket = data_ticket['ticket']
        xpa.expires_ticket = data_ticket['expires_in']
        xpa.save()
    if not create:
        xpa.access_token = access_token
        xpa.expires = expires_in
        xpa.refresh_token = refresh_token
        xpa.save()
    return True


def refresh_public_token_and_info(shop_id):
    """刷新店铺微信token和信息"""
    try:
        wps = WxPublicMapShop.objects.get(shop_id=shop_id, status=WxPublicInfo.STATUS_VALID)
    except WxPublicMapShop.DoesNotExist or WxPublicAccess.DoesNotExist:
        return False

    update_public_token(wps.app_id)
    update_public_info(wps.app_id)
    return True
